<template>
  <div id="app">
    <div class="login" v-if="!isLogin">
      <div class="title">
        <div>周报生成器</div>
        <div class="code-box">
          <img class="code-img" :src="codeImg" alt="" @click="init" />
          <input class="code-input" type="text" v-model="code" />
          <el-button type="primary" class="code-btn" @keyup.enter="login" @click="login" size="mini"
            >一键登录</el-button
          >
        </div>
      </div>
    </div>
    <template v-else>
      <el-button type="danger" v-if="showPDF" class="pdf-btn" @click="toPDF" size="mini"
        >导出PDF</el-button
      >
      <div id="preview">
        <div class="title">
          <div>春知App周报</div>
          <div class="time">{{ startDate }} - {{ endDate }}</div>
        </div>
        <!-- 报表 -->
        <div class="base">
          <div class="week-box">
            <div class="week-table">
              <div
                class="week-item"
                v-for="(item, index) in baseData"
                :key="index"
              >
                <template v-if="index === 0">
                  <div class="week-item-name label">{{ item.name }}</div>
                  <div class="week-item-num label">{{ item.num }}</div>
                  <div class="week-item-num label">{{ item.lastNum }}</div>
                  <div class="week-item-num label">
                    {{ item.differenceNum }}
                  </div>
                </template>
                <template v-else>
                  <div class="week-item-name">{{ item.name }}</div>
                  <div class="week-item-num">{{ item.num }}</div>
                  <div class="week-item-num">{{ item.lastNum }}</div>
                  <div class="week-item-num" :style="{ color: item.color }">
                    {{ item.differenceNum }}
                  </div>
                </template>
              </div>
            </div>
          </div>
        </div>
        <div id="userData" style="width: 1200px;height:400px;"></div>
        <div id="activeData" style="width: 1200px;height:400px;"></div>
        <div id="visitData" style="width: 1200px;height:400px;"></div>
        <div id="startupData" style="width: 1200px;height:400px;"></div>
        <div id="stopData" style="width: 1200px;height:400px;"></div>
        <div id="avgStopData" style="width: 1200px;height:400px;"></div>
        <div id="totalData" style="width: 1200px;height:400px;"></div>
      </div>
    </template>
  </div>
</template>

<script>
import echarts from "echarts";
export default {
  name: "App",
  data() {
    return {
      isLogin: false,
      showPDF:false,
      codeImg: "",
      code: "",
      codeId: "",
      baseData: [],
      userData: null,
      activeData: null,
      visitData: null,
      startupData: null,
      stopData: null,
      avgStopData: null,
      totalData: null,
      startDate: "",
      endDate: "",
      baseName: {
        num_visitor: "访问人数",
        num_visits: "访问次数",
        num_visitor: "入口页次数",
        exit_rate: "退出率",
        num_share: "分享次数",
        visit_avg_time: "次均停留时长",
        visitor_avg_time: "人均停留时长",
        exit_num_visits: "退出页次数",
      },
    };
  },
  created() {
    this.startDate = this.formatDate(
      new Date() - 7 * 24 * 3600 * 1000,
      "yyyy-MM-dd"
    );
    this.endDate = this.formatDate(new Date(), "yyyy-MM-dd");
    this.init();
  },
  methods: {
    async init() {
      let { data: res } = await this.$.get("./code");
      this.codeImg = res.data.img;
      this.code = res.data.code;
      this.codeId = res.data.id;
    },
    async login() {
      try {
        let { data: res } = await this.$.get("./login", {
          params: {
            code: this.code,
            id: this.codeId,
          },
        });
        if (res.data.desc === "ok" && res.data.token) {
          this.isLogin = true;
          this.getData();
        }
      } catch (e) {
        console.log(e);
      }
    },
    async getData() {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.7)",
      });
      try {
        let { data: res } = await this.$.get("./getdata", {
          params: {
            start: this.startDate,
            end: this.endDate,
          },
        });
        let data = res.data;
        for (let key in data.baseData.data) {
          this.baseData.push({
            key: key,
            name: this.baseName[key],
            num: data.baseData.data[key],
            lastNum: data.lastBaseData.data[key],
          });
        }
        this.baseData.map((item, index) => {
          if (
            item.key === "visit_avg_time" ||
            item.key === "visitor_avg_time"
          ) {
            //  如果是时间
            item.differenceNum = this.diffTime(item.num, item.lastNum, index);
          } else if (item.key === "exit_rate") {
            let diff =
              (this.toPoint(item.num) - this.toPoint(item.lastNum)) * 100;
            if (diff > 0) {
              item.color = "red";
            } else {
              item.color = "green";
            }
            item.differenceNum = diff.toFixed(2) + "%";
          } else {
            item.num = String(item.num).replace(/,/g, "");
            item.lastNum = String(item.lastNum).replace(/,/g, "");
            item.differenceNum = item.num - item.lastNum;
            if (item.differenceNum > 0) {
              item.color = "red";
            } else {
              item.color = "green";
            }
          }
          return item;
        });
        this.baseData.unshift({
          name: "-",
          num: "本周数据",
          lastNum: "上周数据",
          differenceNum: "幅度",
        });
        this.userData = data.userData.data;
        this.activeData = data.activeData.data;
        this.visitData = data.visitData.data;
        this.startupData = data.startupData.data;
        this.totalData = data.totalData.data;
        this.stopData = data.stopData.data;
        this.avgStopData = data.avgStopData.data;
        this.draw();
        loading.close();
      } catch (e) {
        console.log(e);
        loading.close();
      }
    },
    toPDF() {
      let preview = document.getElementById("preview");
      this.getPdfFromHtml(preview, `周报${this.startDate}-${this.endDate}`);
    },
    draw() {
      let userOptions = {
        id: "userData",
        title: this.userData.series[0].name,
        xData: this.userData.xAxis,
        yData: this.userData.series[0].data,
      };
      let activeOptions = {
        id: "activeData",
        title: this.activeData.series[0].name,
        xData: this.activeData.xAxis,
        yData: this.activeData.series[0].data,
      };
      let visitOptions = {
        id: "visitData",
        title: this.visitData.series[0].name,
        xData: this.visitData.xAxis,
        yData: this.visitData.series[0].data,
      };

      let startupOptions = {
        id: "startupData",
        title: this.startupData.series[0].name,
        xData: this.startupData.xAxis,
        yData: this.startupData.series[0].data,
      };
      let stopOptions = {
        id: "stopData",
        title: this.stopData.series[0].name,
        xData: this.stopData.xAxis,
        yData: this.stopData.series[0].data,
        axisLabel: {
          formatter: (value, index) => {
            return this.times(value / 1000);
          },
        },
      };
      let avgStopOptions = {
        id: "avgStopData",
        title: this.avgStopData.series[0].name,
        xData: this.avgStopData.xAxis,
        yData: this.avgStopData.series[0].data,
        axisLabel: {
          formatter: (value, index) => {
            return this.times(value / 1000);
          },
        },
      };
      let totalOptions = {
        id: "totalData",
        title: this.totalData.series[0].name,
        xData: this.totalData.xAxis,
        yData: this.totalData.series[0].data,
      };
      this.$nextTick(() => {
        this.drawChart(userOptions);
        this.drawChart(activeOptions);
        this.drawChart(visitOptions);
        this.drawChart(startupOptions);
        this.drawChart(stopOptions);
        this.drawChart(avgStopOptions);
        this.drawChart(totalOptions);
        this.showPDF = true;
      });
    },
    drawChart(options) {
      // 基于准备好的dom，初始化echarts实例
      let myChart = echarts.init(document.getElementById(options.id));
      // 指定图表的配置项和数据
      let option = {
        title: {
          text: options.title,
        },
        xAxis: {
          type: "category",
          data: options.xData,
        },
        yAxis: {
          type: "value",
          axisLabel: options.axisLabel || {},
        },
        series: [
          {
            data: options.yData,
            type: "line",
            smooth: true,
            itemStyle : { normal: {label : {show: true}}},
            areaStyle:{}
          },
        ],
      };
      myChart.setOption(option);
    },
    toPoint(percent) {
      var str = percent.replace("%", "");
      str = str / 100;
      return str;
    },
    diffTime(startTime, endTime, index) {
      let start = this.time_to_sec(startTime);
      let end = this.time_to_sec(endTime);
      let diffTime = start - end;
      console.log(diffTime)
      if (diffTime > 0) {
        this.baseData[index].color = "red";
        return this.times(diffTime);
      } else {
        this.baseData[index].color = "green";
        return this.times( - diffTime);
      }
      //  this.times(diffTime);
    },
    time_to_sec(time) {
      var s = "";
      var hour = time.split(":")[0];
      var min = time.split(":")[1];
      var sec = time.split(":")[2];
      s = Number(hour * 3600) + Number(min * 60) + Number(sec);
      return s;
    },
    times(data) {
      var time = Number(data);
      var h = Math.floor(time / 3600);
      var m = Math.floor((time % 3600) / 60);
      var s = parseInt(time % 3600) % 60;
      var hh = h < 10 ? "0" + h : h;
      var mm = m < 10 ? "0" + m : m;
      var ss = s < 10 ? "0" + s : s;
      return hh + ":" + mm + ":" + ss;
    },
    formatDate(value, fmt, emptyText) {
      fmt = fmt || "yyyy-MM-dd hh:mm:ss";
      if (!value) return emptyText || "";
      let getDate = new Date(value);
      let o = {
        "M+": getDate.getMonth() + 1,
        "d+": getDate.getDate(),
        "h+": getDate.getHours(),
        "m+": getDate.getMinutes(),
        "s+": getDate.getSeconds(),
        "q+": Math.floor((getDate.getMonth() + 3) / 3),
        S: getDate.getMilliseconds(),
      };
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          (getDate.getFullYear() + "").substr(4 - RegExp.$1.length)
        );
      }
      for (let k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
          fmt = fmt.replace(
            RegExp.$1,
            RegExp.$1.length === 1
              ? o[k]
              : ("00" + o[k]).substr(("" + o[k]).length)
          );
        }
      }
      return fmt;
    },
  },
};
</script>

<style lang="scss">
@import "./app.scss";
</style>
